package com.sinodata.bsm.cicp.collector.windows.snmp;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.snmp4j.CommunityTarget;
import org.snmp4j.Snmp;

import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.snmp.GetData;
import com.sinodata.bsm.cicp.util.snmp.MibProcessorEntry;
import com.sinodata.bsm.cicp.util.snmp.OMMappingInfo;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-8-27 下午5:11:18          wangpeng        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class CPUCollector extends SnmpCollector {

    private static final Logger logger = Logger.getLogger(CPUCollector.class);

    @Override
    public List<ResPropertyValue> collect(Snmp snmp, CommunityTarget target) throws CollectorException {
        /**
         * 总的cpu使用大小
         */
        int cpuSumUseRate = -1;

        /**
         * 平均cpu使用率
         */
        int cpuAverageUseRate = -1;

        List<ResPropertyValue> resultList = new ArrayList<ResPropertyValue>();

        try {
            List<OMMappingInfo> cpu = GetData.getAllTableData(snmp, MibProcessorEntry.class, target);
            if (cpu.size() < 1) {
                throw new CollectorException(ip + " snmp没有获取到windows cpu相关数据");
            }
            for (OMMappingInfo mapping : cpu) {
                MibProcessorEntry cpuMapping = (MibProcessorEntry) mapping;
                cpuSumUseRate += cpuMapping.getHrProcessorLoad();
                break;
            }
            cpuAverageUseRate = cpuSumUseRate / cpu.size();
            String[] props = this.getPropMeta();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[props.length];
            for (int i = 0; i < props.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(cpuAverageUseRate + "", props[i]);
            }
            ResPropertyValue resPropertyValue = new ResPropertyValue();
            resPropertyValue.setValues(propValues);
            resultList.add(resPropertyValue);
        } catch (Exception e) {
            logger.error(ip + " windows cpu 采集失败", e);
            throw new CollectorException(e);
        } finally {
            if (snmp != null) {
                try {
                    snmp.close();
                } catch (Exception e2) {
                }
            }
        }
        return resultList;
    }

    @Override
    public String[] getPropMeta() {
        //cpu平均使用率
        return new String[] { "$1" };
    }

    @Override
    public String[] getParamMeta() {
        return null;
    }

}
